const { sendFn, querySql, intercept } = require('../../model/send')
// 密码加密、解密方法
const { encryption } = require('../../dao/bcrypt')
const SystemMethod = {
    // 人员信息查询
    GetUserInfoList: async (req, res) => {
        const UserRes = await querySql(res, `SELECT  * FROM user `, true)
        for (let i = 0; i < UserRes.length; i++) {
            const item = UserRes[i]
            if (item.roleId) {
                const roleIds = item.roleId.split(',')
                const roleRes = await querySql(res, `select * from role where role_id in(${roleIds})`, true)
                item.roleName = roleRes.map(item => item.roleName)
                item.roleId = roleIds
            } else {
                item.roleName = null
            }
        }
        sendFn(res, 200, '获取成功', { userList: UserRes, total: UserRes.length })
    },
    // 新增用户
    AddtUserInfo: async (req, res) => {
        let { userimg, password, name, phone, email, roleId, userInfo, type, remark } = req.body
        // 查询用户账号是否重复
        const userRes = await querySql(res, `SELECT * FROM  user`, true)
        const someRes = userRes.some(item => item === userInfo)
        if (someRes) return sendFn(res, 500, '账号已存在')
        // 通过角色id查询角色名称
        const roleRes = await querySql(res, `select * from role where role_id in(${roleId})`, true)

        const roleNames = roleRes.map(item => item.roleName).join(',')
        // 加密密码
        password = encryption('123456')
        const img = userimg ? userimg : 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
        // 添加数据库
        console.log(type, img, password, userInfo, name, phone, email, roleId.join(','), roleNames)
        const UserRes = await querySql(
            res,
            'INSERT INTO user ( type,userimg, password, username, name, phone,email, role_id, role_name,remark ) value(?,?,?,?,?,?,?,?,?,?)',
            false, [type, img, password, userInfo, name, phone, email, roleId.join(','), roleNames, remark]
        )
        if (UserRes) sendFn(res, 200, '添加成功')
    },
    // 修改人员信息
    EditUserInfo: async (req, res) => {
        let { userInfo, userimg, userid, name, phone, email, roleId, remark, type } = req.body
        console.log(roleId)
        const roleRes = await querySql(res, `select * from role where role_id in(${roleId.join(',')})`, true)
        const roleNames = roleRes.map(item => item.roleName).join(',')
        const UserRes = await querySql(
            res,
            `UPDATE  user SET type='${type}', remark='${remark}', name='${name}',userimg='${userimg}',email='${email}',phone='${phone}',role_name='${roleNames}',role_id='${roleId.join(',')}' where userid=${userid}`
        )
        console.log(roleId)
        if (UserRes) sendFn(res, 200, '修改成功')
    },
    // 删除用户
    DelUserInfo: async (req, res) => {
        await querySql(res, `DELETE FROM  user WHERE userid=${req.body.userId}`)
        sendFn(res, 200, '删除成功')
    },
    // 获取角色列表
    GetRole: async (req, res) => {
        // 查询角色表
        const roleRes = await querySql(res, `SELECT  * FROM role`, true)
        const routers = await querySql(res, `select * from router`, true)
        let tree = []
        tree = routers.filter(item => item.parentId === 0)

        tree.forEach(item => {
            item['children'] = []
            item.label = item.title
            routers.forEach(itemy => {
                itemy.label = itemy.title
                if (item.id == itemy.parentId) item['children'].push(itemy)
            })
        })
        sendFn(res, 200, '获取成功', { roleList: roleRes, routers: tree })
    },
    // 获取角色信息详情
    GetRoleInfo: async (req, res) => {
        // 查询角色表 单条
        const roleRes = await querySql(res, `SELECT  * FROM role WHERE role_id=${req.query.roleId}`, true)

        // 查询角色 绑定的路由 (权限表)
        const authorityRes = await querySql(res, `SELECT  * FROM authority WHERE role_id=${req.query.roleId}`, true)

        // 查询路由 (路由表)
        const routerRes = await querySql(res, `select * from router where id in(${authorityRes[0].routerId})`, true)
        let tree = []
        tree = routerRes.filter(item => item.parentId === 0)

        tree.forEach(item => {
            item['children'] = []
            routerRes.forEach(itemy => {
                if (item.id == itemy.parentId) item['children'].push(itemy)
            })
        })
        sendFn(res, 200, '获取成功', { roleList: roleRes[0], treeDefulat: authorityRes[0].routerId.split(',') })
    },
    // 新增角色
    AddRole: async (req, res) => {
        console.log('insert into role(role_key,role_name,role_authority,remark) value(?,?,?,?)', false, [
            req.body.roleKey,
            req.body.roleName,
            '未填写',
            req.body.remark
        ])
        // 添加数据 添加角色
        const RoleRes = await querySql(
            res,
            'insert into role(role_key,role_name,role_authority,remark) value(?,?,?,?)',
            false, [req.body.roleKey, req.body.roleName, '未填写', req.body.remark]
        )

        // 查询刚刚添加的角色id
        const roleResObj = await querySql(res, `SELECT * FROM  role WHERE role_key='${req.body.roleKey}'`, true)

        // 添加数据 此角色绑定的路由id
        const sqlRes = await querySql(res, 'insert into authority(role_id,router_id) value(?,?)', false, [
            roleResObj[0].roleId,
            req.body.trees
        ])
        if (sqlRes) sendFn(res, 200, '添加成功')
    },
    // 编辑角色
    EditRole: async (req, res) => {
        let sqlRes
        console.log(
            `UPDATE  role  SET role_name = '${req.body.roleName}', role_authority = '${req.body.authority || '未填写'
            }', remark = '${req.body.remark}' WHERE role_id = ${req.body.roleId}`
        )
        sqlRes = await querySql(
            res,
            `UPDATE  role  SET role_name = '${req.body.roleName}', role_authority = '${req.body.authority || '未填写'
            }', remark = '${req.body.remark}' WHERE role_id = ${req.body.roleId}`
        )
        sqlRes = await querySql(
            res,
            `UPDATE  authority  SET router_id = '${req.body.trees}' WHERE role_id = '${req.body.roleId}'`
        )
        if (sqlRes) sendFn(res, 200, '修改成功')
    },
    // 删除角色
    DelRoleInfo: async (req, res) => {
        // 删除用户绑定的角色id
        const userRes = await querySql(res, `SELECT * FROM  user`, true)
        let roleNames
        for (let i = 0; i < userRes.length; i++) {
            const item = userRes[i]
            if (item.roleId) {
                const arr = item.roleId.split(',')
                const inf = arr.findIndex(itemx => itemx == req.body.roleId)
                if (inf !== -1) {
                    arr.splice(inf)
                    if (arr.length > 0) {
                        const roleRes = await querySql(res, `select * from role where role_id in(${arr.join(',')})`, true)
                        roleNames = roleRes.map(itemy => itemy.roleName).join(',')
                    } else {
                        roleNames = []
                    }
                    await querySql(
                        res,
                        `UPDATE  user SET name='${item.name}',userimg='${item.userimg}',email='${item.email}',phone='${item.phone
                        }',role_name='${roleNames}',role_id='${arr.join(',')}' where userid=${item.userid}`
                    )
                }
            }
        }

        // 删除权限表角色id
        await querySql(res, `DELETE FROM  authority WHERE role_id=${req.body.roleId}`)
        const sqlRes = await querySql(res, `DELETE FROM role where role_id=${req.body.roleId}`)
        if (sqlRes) sendFn(res, 200, '删除成功')
    },
    // 添加 菜单路由
    AddRouter: async (req, res) => {
        let parent_Id = 0
        let { icon, isShow, keepAlive, name, parentId, path, title, type, viewPath } = req.body
        // type为0代表是父级 强制 parent_Id 为 0
        parentId.length > 1 ? (parentId = 0) : (parentId = parentId)
        // 是否有path
        path = path.length > 1 ? path : '/' + name
        // 是否有文件路径
        viewPath = viewPath.length > 2 ? viewPath : 'null'
        // 是否显示 1为显示 0 不显示
        isShow = isShow ? 1 : 0
        // 'insert into role(role_key,role_name,role_authority,remark) value(?,?,?,?)', false, [req.body.roleKey, req.body.roleName, '未填写', req.body.remark]
        const sqlRes = await querySql(
            res,
            'insert into router(name,title,parent_Id,view_path,path,type,icon,is_show,keep_alive) value(?,?,?,?,?,?,?,?,?)',
            false, [name, title, parentId, viewPath, path, type, icon, isShow, keepAlive]
        )
        if (sqlRes) sendFn(res, 200, '添加成功')
    },
    // 修改 菜单路由
    EditRouter: async (req, res) => {
        let { icon, isShow, keepAlive, name, parentId, path, title, type, viewPath, id } = req.body
        // type为0代表是父级 强制 parent_Id 为 0
        parentId.length > 1 ? (parentId = 0) : (parentId = parentId)
        // 是否有path
        path = path.length > 1 ? path : '/' + name
        // 是否有文件路径
        console.log(viewPath)
        if (viewPath) {
            viewPath = viewPath.length > 2 ? viewPath : 'null'
            viewPath = null
        }
        // 是否显示 1为显示 0 不显示
        // isShow = isShow ? 1 : 0
        await querySql(
            res,
            `UPDATE  router  SET
    icon = '${icon}',
    is_show = ${isShow},
    keep_alive = ${keepAlive},
    name = '${name}',
    parent_id = ${parentId},
    path = '${path}',
    title = '${title}',
    type = ${type},
    view_path = '${viewPath}'
      WHERE id = '${id}'`
        )
        sendFn(res, 200, '修改成功')
    },
    // 获取菜单路由列表
    GetRouterList: async (req, res) => {
        const routerRes = await querySql(res, `select * FROM router`, true)
        sendFn(res, 200, '获取成功', { routerRes, total: routerRes.length })
    },
    // 删除菜单路由
    DelRouterList: async (req, res) => {
        const routerRes = await querySql(res, `SELECT * FROM  router`, true)
        const authorityRes = await querySql(res, `SELECT * FROM  authority`, true)
        for (let i = 0; i < authorityRes.length; i++) {
            const item = authorityRes[i]
            if (item.routerId.length > 0) {
                const routerIds = item.routerId.split(',')
                // 寻找与删除id相同的id
                const findInd = routerIds.findIndex(itemy => itemy == req.body.id)
                // 找出下标删除
                if (findInd !== -1) routerIds.splice(findInd)
                // 删除后的结果在填写给sql
                await querySql(
                    res,
                    `UPDATE  authority  SET router_id = '${routerIds}' WHERE authority_id = '${item.authorityId}'`
                )
            }
        }
        // 查询是否删除的为父级
        const parentId = routerRes.filter(item => req.body.id === item.parentId)
        const delRouterIDs = parentId.map(item => item.id).join(',')
        console.log(delRouterIDs.length)
        // 如果是父级且子级有路由就一起删除掉
        const Ids = delRouterIDs.length > 0 ? delRouterIDs + ',' + req.body.id : req.body.id
        await querySql(res, `DELETE FROM  router WHERE id in (${Ids})`)
        sendFn(res, 200, '删除成功')
    }
}
module.exports = SystemMethod